package cn.tedu.ivos3.application.service.impl;

import cn.tedu.ivos3.application.mapper.ApplicationMapper;
import cn.tedu.ivos3.application.pojo.dto.ApplicationQuery;
import cn.tedu.ivos3.application.pojo.dto.ApplicationSaveParam;
import cn.tedu.ivos3.application.pojo.entity.Application;
import cn.tedu.ivos3.application.pojo.vo.ApplicationVO;
import cn.tedu.ivos3.application.service.ApplicationService;
import cn.tedu.ivos3.audit.mapper.AuditMapper;
import cn.tedu.ivos3.audit.pojo.vo.AuditVO;
import cn.tedu.ivos3.audit.service.AuditService;
import cn.tedu.ivos3.base.enums.ApplicationStatusEnum;
import cn.tedu.ivos3.base.enums.AuditStatusEnum;
import cn.tedu.ivos3.base.response.StatusCode;
import cn.tedu.ivos3.user.mapper.UserMapper;
import cn.tedu.ivos3.user.pojo.entity.User;
import cn.tedu.ivos3.user.pojo.vo.UserVO;
import cn.tedu.ivos3.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos3.vehicle.pojo.entity.Vehicle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

@Slf4j
@Service
public class ApplicationServiceImpl implements ApplicationService {
    @Autowired
    ApplicationMapper applicationMapper;
    @Autowired
    AuditService auditService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AuditMapper auditMapper;
    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public void save(ApplicationSaveParam applicationSaveParam) {
        log.debug("新增申请单业务参数：{}", applicationSaveParam);
        Application application = new Application();
        BeanUtils.copyProperties(applicationSaveParam, application);
        application.setStatus(ApplicationStatusEnum.PENDING.getCode());
        application.setCreateTime(new Date());
        /* 遇到的问题：新增申请单对应的审批单时,审批单数据没有此申请单id
           原因：执行insert方法的SQL时，并没有把刚刚生成的申请单id回填到applicaton对象中
           解决办法：给此SQL上加useGeneratedKeys="true" keyProperty=“id”属性
           效果：JDBC自动回填此申请单id到application对象的id属性中，再传给审批，审批就拿到申请单id了
         */
        applicationMapper.insert(application);
        //还需要为当前申请单生成对应的审批单数据
        auditService.insertAudit(application);
    }

    @Override
    public List<ApplicationVO> selectApplication(ApplicationQuery applicationQuery) {
        log.debug("查询申请单业务:applicationQuery={}", applicationQuery);
        List<ApplicationVO> list = applicationMapper.selectApplication(applicationQuery);
        //遍历申请单集合，依次为每一个申请单VO补全审批人数据
        for (int i = 0; i < list.size(); i++) {
            ApplicationVO applicationVO = list.get(i);
            //为当前遍历到的申请单VO补全数据
            assignAuditUserList(applicationVO);
        }
        return list;
    }

    /**
     * 本方法用于给当前传入的ApplicationVO补全审批人数据，注意：不会产生新的ApplicationVO!!!
     * 审批人id集合List<Long> auditUserIdList; =>[106,103]
     * 审批人姓名字符串 String auditUsername;=>"moly,tom"
     *
     * @param applicationVO
     */
    private void assignAuditUserList(ApplicationVO applicationVO) {
        //1.准备空集合，分别用来保存当前申请单对应的审批单id与姓名
        List<Long> auditUserIdList = new ArrayList<>();
        List<String> auditUsernameList = new ArrayList<>();
        //2.根据当前申请单id,查询批此申请单的所有审批单====》得到多个审批单集合
        List<AuditVO> auditVOList =
                auditService.selectAuditByApplicationId(applicationVO.getId());
        //遍历每一个审批单
        for (int i = 0; i < auditVOList.size(); i++) {
            AuditVO auditVO = auditVOList.get(i);
            //4.取出当前审批单的审批人id并存入空的id集合中
            Long id = auditVO.getAuditUserId();
            auditUserIdList.add(id);
            //5.根据审批人id，查询审批人姓名
            UserVO userVO = userMapper.selectById(id);//根据id查姓名
            auditUsernameList.add(userVO.getUsername());
        }
        //6.准备一个拼接工具，帮我们将多个审批人姓名连成指定格式的字符串
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String username : auditUsernameList) {
            stringJoiner.add(username);
        }
        //7，将准备好的审批人姓名字符串与审批人id集合赋值给当前传入的ApplicationVO
        applicationVO.setAuditUsernameList(stringJoiner.toString());
        applicationVO.setAuditUserIdList(auditUserIdList);
    }

    @Override
    public void cancel(Long id) {
        log.debug("撤销申请单业务id参数：{}", id);
        Application application = new Application();
        application.setId(id);
        application.setStatus(AuditStatusEnum.CANCEL.getCode());
        application.setCreateTime(new Date());
        applicationMapper.update(application);

        //除此之外，还需要删除审批单的所有审批单
        auditMapper.deleteByApplicationId(id);
    }

    @Override
    public void distribute(Long applicationId, Long vehicleId) {
        log.debug("分配车辆业务：{}", applicationId);
        Application application = new Application();
        application.setId(applicationId);
        application.setVehicleId(vehicleId);
        application.setStatus(ApplicationStatusEnum.ALLOCATION.getCode());
        application.setUpdateTime(new Date());
        applicationMapper.update(application);

        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setStatus("2");
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }

    @Override
    public void back(Long applicationId, Long vehicleId) {
        log.debug("归还车辆业务：{}", applicationId, vehicleId);
        Application application = new Application();
        application.setId(applicationId);
        application.setVehicleId(vehicleId);
        application.setStatus(ApplicationStatusEnum.END.getCode());
        application.setUpdateTime(new Date());
        /* 方案1：申请单设置为结束，但车辆id依旧保留 */
        //application.setVehicleId(vehicleId);
        //applicationMapper.update(application);
        /* 方案2：申请单设置为结束，车辆id设置为null*/
        application.setVehicleId(null);
        applicationMapper.back(application);//写一个新的SQL设置null值

        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setStatus("1");
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }
}
